<template>
  <div class="tob">
    <!--搜索-->
    <div slot="header" class="clearfix">
      <el-divider />
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="工单信息查询：" prop="mobile">
          <el-input v-model="mobile" placeholder="请输入工单信息" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="info" @click="resetQuery">重置</el-button>
          <el-button
            icon="el-icon-circle-plus-outline"
            type="success"
            @click="handleAdd"
          >新增订单</el-button>

          <el-popover
            v-model="visible"
            class="delete"
            placement="top"
            width="160"
          >
            <p>确定删以下用户吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="visible = false"
              >取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleBatchDel"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              icon="el-icon-delete"
              type="danger"
            >批量删除
            </el-button>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <!--渲染table表格-->
    <template>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="selsChange"
      >
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" />
        <el-table-column prop="title" label="订单名称" />
        <el-table-column prop="type" label="订单类型" />
        <el-table-column prop="domain" label="业务领域" />
        <el-table-column prop="status" label="订单状态">
          <template slot-scope="scope">
            {{ scope.row.status === 0 ? '待支付' : scope.row.status === 1 ? '勘测中' :scope.row.status===2?'已勘测' :scope.row.status===3?'安装中':scope.row.status===4?'已完成':scope.row.status===5?'已取消':scope.row.status===6?'已退款':"未知状态" }}
          </template>
        </el-table-column>
        <el-table-column prop="tel" label="联系手机" />

        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="examine(scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="SurveyPicture(scope.row.id)">勘测图片</el-button>
            <el-button type="text" size="small" @click="uploadInstallReport(scope.row.id)">施工方案上传</el-button>
            <el-button type="text" size="small" @click="FinishedPicture(scope.row.id)">完工图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 新增订单弹窗 -->
    <!-- 新增订单弹窗 -->
    <!-- 新增订单弹窗 -->
    <!-- 新增订单弹窗 -->
    <!-- 新增订单弹窗 -->
    <!-- 新增订单弹窗 -->
    <el-dialog width="700px" :visible.sync="conceal" title="新增订单">
      <el-form ref="dataList" label-width="120px" :model="dataList" :rules="rules">
        <el-form-item label="订单名称" prop="title">
          <el-input v-model="dataList.title" size="small" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="订单类型" prop="type">
          <el-input v-model="dataList.type" size="small" placeholder="请输入订单类型" />
        </el-form-item>
        <el-form-item label="业务领域" prop="domain">
          <el-input v-model="dataList.domain" size="small" placeholder="业务领域" />
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="dataList.tel" size="small" placeholder="业务领域" />
        </el-form-item>

        <el-form-item label="订单状态" prop="gender">
          <el-select v-model.number="dataList.status" placeholder="请选择订单状态" @change="handleReceiverChange">
            <el-option
              v-for="option in roleTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <!-- 确认和取消按钮 -->
        <el-form-item>
          <el-button size="mini" type="primary" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--分配师傅编辑弹窗-->
    <!--分配师傅编辑弹窗-->
    <!--分配师傅编辑弹窗-->
    <!--分配师傅编辑弹窗-->
    <el-dialog width="700px" :visible.sync="open" :title="title">
      <el-form ref="formData" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="订单名称" prop="title">
          <el-input v-model="formData.title" size="small" placeholder="请输入订单类型" />
        </el-form-item>
        <el-form-item label="订单类型" prop="type">
          <el-input v-model="formData.type" size="small" placeholder="请输入订单类型" />
        </el-form-item>
        <el-form-item label="订单编号" prop="id">
          <el-input v-model="formData.id" size="small" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="业务领域" prop="domain">
          <el-input v-model="formData.domain" size="small" placeholder="业务领域" />
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="formData.tel" size="small" placeholder="业务领域" />
        </el-form-item>
        <el-form-item label="下单时间" prop="createdAt">
          <el-input v-model="formData.createdAt" size="small" placeholder="下单时间" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-input v-model="formData.updatedAt" size="small" placeholder="更新时间" />
        </el-form-item>
        <el-form-item label="订单状态" prop="gender">
          <el-select v-model.number="formData.status" placeholder="请选择订单状态" @change="handleReceiverChange">
            <el-option
              v-for="option in roleTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="受理人ID" prop="gender">
          <el-select v-model="formData.acceptorId" placeholder="受理人ID" @change="handleReceiverChange">
            <el-option
              v-for="option in receiver"
              :key="option.value"
              :label="option.nickName"
              :value="option.id"
            />
          </el-select>
        </el-form-item>

        <!-- 确认和取消按钮 -->
        <el-form-item>
          <el-button size="mini" type="primary" @click="update">确定</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看图片 -->
    <!-- 查看图片 -->
    <!-- 查看图片 -->
    <!-- 查看图片 -->
    <el-dialog width="700px" :visible.sync="ensconce" :title="title">
      <div v-for="(item, index) in imageList" :key="index" class="demo-image__preview">
        <el-image
          v-if="imageList[index] !== ''"
          style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%"
          :src="imageList[index]"
          :preview-src-list="item.imageList"
        />
      </div>

    </el-dialog>
    <el-dialog width="700px" :visible.sync="shutOpen" :title="title">
      <div v-for="(item, index) in imageData" :key="index" class="demo-image__preview">
        <el-image
          v-if="imageData[index] !== ''"
          style="width: 600px; height: 400px;border: 1px solid #000; margin-bottom: 5px;margin-left: 5%;"
          :src="imageData[index]"
          :preview-src-list="item.imageData"
        />
      </div>
    </el-dialog>
    <!-- 文件上传弹窗 -->
    <el-dialog width="700px" :visible.sync="FileHiding" :title="title">
      <span>工单id: </span>
      <input v-model="sheetId" type="text" placeholder="Enter Sheet ID"><br><br>
      <input type="file" @change="onFileChange"><br><br>
      <button @click="uploadFile">点击上传</button><br><br>
      <div v-if="message">{{ message }}</div>
    </el-dialog>
    <!-- 查看文件路径 -->
    <el-dialog width="700px" :visible.sync="inquire" :title="title" :model="ossFileDTO">
      <el-form label-width="120px">
        <el-form-item label="施工文档路径">
          <a :href="ossFileDTO" style="color: #1d82fe;">{{ ossFileDTO }}</a>
        </el-form-item>
      </el-form>
    </el-dialog>

    <template>
      <el-row style="height: 60px" justify="end" class="middle">
        <el-pagination
          :page-size="pageParams.pageSize"
          :current-page="pageParams.currentPage"
          :total="pageParams.resultCount"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,prev, pager, next,jumper"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </template>
  </div>
</template>

<script>
import { listRole, getRole, updateRole, listRoleAPI, listData, deleteRole, addRole } from '@/api/order/ElectricianOrder'
import request from '@/utils/request'
export default {
  data() {
    return {
      tableData: [],
      open: false,
      conceal: false,
      // 图片弹窗
      ensconce: false,
      shutOpen: false,
      title: '编辑工单',
      visible: false, // 初始化为 false 或 true，根据实际情况设定
      // 文件上传弹窗
      FileHiding: false,
      // 文件查询
      inquire: false,
      file: null,
      sheetId: '',
      message: '',
      // 分页数据
      pageParams: {
        currentPage: 1,
        pageSize: 10,
        resultCount: 0
      },
      // 勘测图片
      imageList: '',
      imageData: '',
      // 编辑弹窗数据回填
      // formData: '',
      // 模糊查询功能
      mobile: '',
      // 数据范围选项
      roleTypeOptions: [
        {
          value: 0,
          label: '待支付'
        },
        {
          value: 1,
          label: '勘测中'
        },
        {
          value: 2,
          label: '已勘测'
        },
        {
          value: 3,
          label: '安装中'
        },
        {
          value: 4,
          label: '已完成'
        },
        {
          value: 5,
          label: '已取消'
        },
        {
          value: 6,
          label: '退款中'
        },
        {
          value: 7,
          label: '已退款'
        }
      ],
      // 角色分页查询
      // 分页数据
      paging: {
        currentPage: 1,
        pageSize: 10,
        resultCount: 0
      },
      // 存储数据
      formData: {},
      // 新增数据
      dataList: {},
      // 存储角色id
      roleId: {},
      userId: [],
      // 施工路径
      ossFileDTO: '',
      // 受理人ID
      receiver: {},
      form: {
        receiverId: '' // 存储当前选择的用户id
      },
      rules: {
        type: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }],
        domain: [{ required: true, message: '业务领域不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '数据是否有效不能为空', trigger: 'blur' }],
        createdAt: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        updatedAt: [
          { required: true, message: '更新时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.formList()
    this.getList()
  },
  methods: {

    async formList() {
      const res = await listRole(this.pageParams.currentPage, this.pageParams.pageSize, this.mobile)
      console.log(res, '渲染数据')
      this.tableData = res.data
      this.pageParams.currentPage = res.currentPage
      this.pageParams.pageSize = res.pageSize
      this.pageParams.resultCount = res.resultCount
    },
    // 编辑弹窗
    async handleUpdate(id) {
      this.open = true
      const res = await getRole(id)
      console.log(res)
      this.formData = res
    },

    // 获取角色id
    async getList() {
      const res = await listRoleAPI(this.paging.currentPage, this.paging.pageSize)
      // console.log(res)
      // 将roleId保存在局部变量中
      const roleId = res.data[0].id.toString()
      // 调用getData，并传递roleId作为参数
      this.getData(roleId)
    },
    // 获取查询商户拿用户id
    async getData(roleId) {
      const res = await listData(roleId, this.paging.currentPage, this.paging.pageSize)
      this.receiver = res.data
      console.log(this.receiver, '商户')
    },
    // 完功图片
    async FinishedPicture(id) {
      this.ensconce = true
      this.title = '完工图片'
      const res = await getRole(id)
      console.log(res)
      this.imageList = res.installPictureList
      console.log(this.imageList)
    },
    // 勘测图片
    async SurveyPicture(id) {
      this.shutOpen = true
      this.title = '勘测图片'
      const res = await getRole(id)
      console.log(res)
      this.imageData = res.surveyPictureList
      console.log(this.imageData)
    },

    // 监听选择用户的id
    handleReceiverChange(id) {
      console.log(id, 'wqqw')
      this.form.receiverId = id
      console.log('当前选择的用户ID1', this.form.receiverId)
      // 在这里可以获取到当前选择的用户id，进行需要的逻辑处理
    },
    // 取消新增功能
    reset() {
      this.dataList = {
        title: '',
        type: '',
        domain: '',
        createdAt: '',
        updatedAt: '',
        gender: '',
        status: '',
        acceptorId: ''
        // 表单验证
      }
    },
    // 新增订单弹窗
    async handleAdd() {
      this.conceal = true
    },
    // 新增订单
    async btnPermissionOK() {
      const isOK = await this.$refs.dataList.validate()
      if (isOK) {
        await addRole(this.dataList)
        this.$message.success('手动新增订单成功')
        this.conceal = false
        this.formList()
        this.reset()
      }
    },
    close() {
      this.$message.success('取消新增订单成功')
      this.conceal = false
      this.formList()
      this.reset()
    },
    // 通过用户id进行修改订单
    async update() {
      const isOK = await this.$refs.formData.validate()
      if (isOK) {
        const res = await updateRole(this.formData, this.form.receiverId)
        console.log(res, '222')
        this.$message.success('分配电工师傅成功')
        this.open = false
        this.formList()
        console.log(res)
      }
    },
    // 分页变化时的处理函数
    handleCurrentChange(page) {
      this.pageParams.currentPage = page
      this.formList()
    },
    // 批量删除勾选存储数据
    selsChange(row) {
      this.sels = [...row]
    },
    // 批量删除
    async handleBatchDel() {
      const idsAsString = this.sels.map((item) => item.id.toString())
      try {
        await deleteRole(idsAsString)
        this.$message('删除成功')
        this.visible = false
        this.formList()
      } catch (error) {
        console.error(error)
        this.$message.error('删除失败')
      }
    },
    // 搜索功能
    handleQuery() {
      this.pageParams.currentPage = 1
      this.formList()
    }, // 重置
    resetQuery() {
      this.mobile = ''
      this.handleQuery()
    },
    // 取消弹窗
    cancel() {
      this.open = false
    },
    // 文件上传
    // 文件上传
    // 文件上传

    async uploadInstallReport(id) {
      this.FileHiding = true
      this.title = '文件上传'
      const res = await getRole(id)
      this.sheetId = res.id
      console.log(res)
    },
    // el-upload文件上传事件
    onFileChange(event) {
      console.log(event)
      this.file = event.target.files[0]
      console.log(this.file, ' this.file ')
    },
    uploadFile() {
      if (!this.sheetId) {
        this.message = 'Please enter Sheet ID'
        return
      }
      if (!this.file) {
        this.message = 'Please select a file'
        return
      }
      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('sheetId', this.sheetId)
      formData.append('file', this.file)
      // 发送 POST 请求
      request.post('/sheet/generInstallReport', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          if (response === true) {
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            this.FileHiding = false
          }
        })
        .catch(error => {
          // 处理错误
          console.error('Error uploading file:', error)
          this.message = 'Error uploading file'
        })
    },
    // 查看施工方案
    async examine(id) {
      this.inquire = true
      this.title = '查看施工方案'
      const res = await getRole(id)
      console.log(res)
      this.ossFileDTO = res.wordFileUrl
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 95%;
  margin: 2.5%;
}

.block {
  text-align: center;
  margin-top: 20px;
}
.delete {
  margin-left: 10px;
}
</style>
